package com.cyp.blogsystem.service.impl;

import com.cyp.blogsystem.exception.BusinessException;
import com.cyp.blogsystem.mapper.ArticleMapper;
import com.cyp.blogsystem.mapper.CommentMapper;
import com.cyp.blogsystem.model.query.CommentQuery;
import com.cyp.blogsystem.model.request.CreateCommentRequest;
import com.cyp.blogsystem.model.vo.CommentVO;
import com.cyp.blogsystem.pojo.Article;
import com.cyp.blogsystem.pojo.Comment;
import com.cyp.blogsystem.pojo.PageResult;
import com.cyp.blogsystem.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CommentServiceImpl implements CommentService {

  private final CommentMapper commentMapper;
  private final ArticleMapper articleMapper;

  @Override
  @Transactional
  public Long createComment(Long userId, CreateCommentRequest request) {
    // 1. 校验文章是否存在
    Article article = articleMapper.selectById(request.getArticleId());
    if (article == null) {
      throw new BusinessException("文章不存在");
    }

    // 2. 创建评论
    // 2.1 构建评论对象
    Comment comment = new Comment();
    comment.setArticleId(request.getArticleId());
    comment.setUserId(userId);
    comment.setContent(request.getContent());
    comment.setStatus(1);

    // 2.2 保存评论
    commentMapper.insert(comment);

    // 3. 更新文章评论数
    articleMapper.incrementCommentCount(request.getArticleId());

    // 4. 返回评论ID
    return comment.getId();
  }

  @Override
  public PageResult<CommentVO> getCommentList(CommentQuery query) {
    // 查询总数
    long total = commentMapper.selectCount(query);
    if (total == 0) {
      return PageResult.empty();
    }

    // 查询列表
    List<Comment> comments = commentMapper.selectList(query);
    List<CommentVO> voList = comments.stream()
        .map(this::convertToVO)
        .collect(Collectors.toList());

    return PageResult.of(total, voList);
  }

  @Override
  @Transactional
  public void deleteComment(Long id) {
    Comment comment = commentMapper.selectById(id);
    if (comment == null) {
      throw new BusinessException("评论不存在");
    }

    // 删除评论
    commentMapper.deleteById(id);
    // 更新文章评论数
    articleMapper.decrementCommentCount(comment.getArticleId());
  }

  private CommentVO convertToVO(Comment comment) {
    CommentVO vo = new CommentVO();
    BeanUtils.copyProperties(comment, vo);
    // 设置其他属性...
    return vo;
  }
}